import Input from "@/components/Input";
import NavBar from "@/components/NavBar";
import styles from "./index.module.scss";
import { useFormik } from "formik";

import * as Yup from "yup";
import { useEffect, useRef, useState } from "react";
import { loginAction, sendCodeAction } from "./../../store/action/user";
import { useAppDispatch } from "@/store";
import { useHistory, useLocation } from "react-router-dom";
import { ILoginState } from "@/components/AuthRoute/AuthRoute";

export default function Login() {
  const [second, setSecond] = useState(0);
  const dispatch = useAppDispatch();
  const history = useHistory();
  const { state } = useLocation<ILoginState>();
  const { fromPath } = state || {};

  const formik = useFormik({
    initialValues: {
      mobile: "13511115555",
      code: "",
    },
    onSubmit: async (values) => {
      await dispatch(loginAction(values.mobile, values.code));
      history.push(fromPath || "/");
    },

    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required("不能为空")
        .matches(/^1[3-9]\d{9}$/, "请输入11位手机号码"),
      code: Yup.string()
        .required("不能为空")
        .matches(/\d{6}/, "请输入6位验证码"),
    }),
  });

  const timerIdRef = useRef(0);

  const handleSendCode = () => {
    dispatch(sendCodeAction(formik.values.mobile));
    setSecond(60);

    timerIdRef.current = window.setInterval(() => {
      setSecond((preSecond) => {
        if (preSecond === 1) {
          clearInterval(timerIdRef.current);
        }
        return preSecond - 1;
      });
    }, 100);
  };
  useEffect(() => {
    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          <Input
            autoFocus
            className="input"
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ""}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <Input
            className="input"
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formik.touched.code ? formik.errors.code : ""}
            extra={
              second === 0 ? (
                <div onClick={handleSendCode} className="extra">
                  获取验证码
                </div>
              ) : (
                <span className="extra">{`${second}秒后获取`}</span>
              )
            }
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <button type="submit" className="login-btn" disabled={false}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
